package com.spyx.auth;

import com.atyx.spyx.vo.user.UserLoginVo;
import com.spyx.common.JwtHelper;
import com.spyx.constant.RedisConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserLoginInterceptor implements HandlerInterceptor {
    private RedisTemplate redisTemplate;//使用构造方法，传递过来一个redisTemplate

    public UserLoginInterceptor(RedisTemplate redisTemplate){
        this.redisTemplate=redisTemplate;
    }


    @Override   //返回true表示继续执行 ，返回false表示拦截，不允许继续执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器被执行--------");
        //1.从请求头中获取token
        String token = request.getHeader("token");
        //2.获取token中的userId
        if(!StringUtils.isEmpty(token)){
            Long userId = JwtHelper.getUserId(token);
            //3.从redis中获取，根据userId获取登录的用户信息 userLoginVo
            UserLoginVo userLoginVo = (UserLoginVo) redisTemplate.opsForValue().get(RedisConst.USER_LOGIN_KEY_PREFIX + userId);
            //4.将登录信息存储到AuthContextHolder类中的Threadlocal中
            AuthContextHolder.setUserId(userLoginVo.getUserId());
            AuthContextHolder.setWareId(userLoginVo.getWareId());
            AuthContextHolder.setUserLoginVo(userLoginVo);
        }
        return true;
    }
}
